#include "thread.h"
#include "ui_thread.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/un.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/types.h>
#include <linux/netlink.h>
#include <errno.h>
#include <unistd.h>

static int init_hotplug_sock(void)
{
    struct sockaddr_nl snl;
    const int buffersize = 16 * 1024 * 1024;
    int retval;
    memset(&snl, 0x00, sizeof(struct sockaddr_nl));
    snl.nl_family = AF_NETLINK;
    snl.nl_pid = getpid();
    snl.nl_groups = 1;
    int hotplug_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
    if (hotplug_sock == -1) {
        printf("error getting socket: %s", strerror(errno));
        return -1;
    }
    /* set receive buffersize */
    setsockopt(hotplug_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
    retval = bind(hotplug_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
    if (retval < 0) {
        printf("bind failed: %s", strerror(errno));
        close(hotplug_sock);
        hotplug_sock = -1;
        return -1;
    }
    return hotplug_sock;
}


Thread::Thread(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Thread)
{
    ui->setupUi(this);

    pushButton = new QPushButton(this);
    pushButtonSDCheck=new QPushButton(this);
    workerThread = new WorkerThread(this);
    workerThreadmove = new WorkerThreadMove(this);

    /* 按钮设置大小与文本 */
    pushButton->resize(200, 100);
    pushButton->setText("Start");
    pushButton->move(200,300);

    pushButtonSDCheck->resize(200, 100);
    pushButtonSDCheck->setText("StartCheck_U");
    pushButtonSDCheck->move(100,200);

    StoppushButton = new QPushButton(this);

    /* 信号槽连接 */
    connect(workerThreadmove, SIGNAL(resultReadyMove(QString)),
            this, SLOT(resultReadyMove(QString)));
    connect(workerThread, SIGNAL(resultReady(QString)),
            this, SLOT(resultReady(QString)));

    connect(pushButton, SIGNAL(clicked()),
            this, SLOT(pushButtonClicked()));
    connect(pushButtonSDCheck, SIGNAL(clicked()),
            this, SLOT(pushButtonSDCheckClicked()));
}

Thread::~Thread()
{
    delete ui;
}

void Thread::pushButtonClicked()
{
    /* 检查线程是否在运行，如果没有则开始运行 */
    if (!workerThread->isRunning())
        workerThread->start();
}

void Thread::pushButtonSDCheckClicked()
{
    /* 检查线程是否在运行，如果没有则开始运行 */
    if (!workerThreadmove->isRunning())
        workerThreadmove->start();
}

void Thread::handleResults(const QString &result)
{
    static int i;
    /* 打印出线程发送过来的结果 */
    qDebug()<<result<<endl;
    i++;
    pushButton->move(10*i,10*i);
    if(i==40)i=0;
}

void WorkerThread::CheckIsDevice(int plug_sock)
{
    char buf[2048] = {0};
    recv(plug_sock, &buf, sizeof(buf), 0);

    QString result = buf;
    while(result.contains("add")||result.contains("remove"))
    {
        result = buf;
        if(result.contains("add"))
        {
            if (result.contains("sda1"))
            {
                 system("mount /dev/sda1 /opt/SD");
                 sync();
                 printf("sda1.....mount ok!!...........\n");
            }
            else if (result.contains("sdb1"))
            {
                 system("mount /dev/sdb1 /opt/SD");
                 sync();
                 printf("sdb1......mount ok!!.............\n");
            }
            else if (result.contains("sdc1"))
            {
                 system("mount /dev/sdc1 /opt/SD");
                 sync();
                 printf("sdc1....mount ok!!................\n");
            }
        }
        else if(result.contains("remove"))
        {
            if (result.contains("sda1"))
            {
                system("umount /dev/sda1");
                sync();
                printf("-----------------------umount sda1-------------------------------\n");
            }
            else if (result.contains("sdb1"))
            {
                system("umount /dev/sdb1");
                sync();
                printf("-----------------------umount sdb1-------------------------------\n");
            }
            else if (result.contains("sdc1"))
            {
                system("umount /dev/sdc1");
                sync();
                printf("-----------------------umount sdc1-------------------------------\n");
            }
        }
        memset(buf,0,1024);
    }
}

void WorkerThread::run()
{
     QString result = "start OK!!";
     int hotplug_sock= init_hotplug_sock();
     while(1)
     {
       CheckIsDevice(hotplug_sock);
      //  sleep(1);
      // qDebug()<<"thread is Runing!!!!!";
      //  emit resultReady(result);
     }

}

void WorkerThreadMove::run()
{
     QString result = "start OK!!";
  //   int hotplug_sock= init_hotplug_sock();
     while(1)
     {
  //     CheckIsDevice(hotplug_sock);
        sleep(1);
        qDebug()<<"thread is Runing!!!!!";
        emit resultReadyMove(result);
     }

}


